/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlets;

import data.Auth;
import data.DataProvider;
import data.PhotoCache;
import entities.ArtPhoto;
import entities.User;
import exceptions.AuthException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONArray;
import org.json.JSONObject;

/**
 *
 * @author bertram
 */
public class Photos extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        User user = null;
        try {
            user = new Auth().checkAuth(request);
        } catch (AuthException aux) {
        }
        response.setContentType("application/json;charset=UTF-8");
        Map params = request.getParameterMap();
        PrintWriter out = response.getWriter();
        try {
            String action = request.getRequestURI().split("photos/")[1];

            if (action.equals("cache")) {
                String str = request.getParameter("data");
                try {
                    JSONArray arr = new JSONArray(str);
                    System.out.println("json: " + arr.toString());
                    ArrayList<ArtPhoto> photos = new ArrayList<ArtPhoto>();
                    DataProvider prov = new DataProvider();

                    for (int i = 0; i < arr.length(); i++) {
                        photos.add(prov.getPhoto(arr.getInt(i)));
                    }
                    String token = PhotoCache.addPhotos(photos);
                    JSONObject obj = new JSONObject();
                    obj.put("cacheID", token);
                    out.write(obj.toString());
                } catch (Exception jex) {
                    System.out.println("nej, ikke json" + jex.getMessage());
                }
            } else  {
                boolean nonatt = false;
                if (action.endsWith("byuser/")) {
                    nonatt = false;
                }
                if(action.endsWith("nonatt")){
                    nonatt = true;
                }
                    DataProvider prov = new DataProvider();
                    int userId = user.getInstitution().getId();
                    ArrayList<ArtPhoto> photos = prov.getPhotosByInstID(userId, nonatt);
                    JSONObject obj = new JSONObject();
                    JSONArray arr = new JSONArray();
                    for (ArtPhoto pht : photos) {
                        arr.put(pht.toJson());
                    }
                    try {
                        obj.put("photos", arr);
                        out.write(obj.toString());
                    } catch (Exception ex) {
                        System.out.println("fejlede json igen" + ex.getMessage());

                    }
                }
            

        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
